<template>
  <layout
    tabbar="/pages/message/index"
    navbar="none"
    :showBack="false"
    class="dark-theme"
    navbarBackgroundColor="#020303"
  >
    <view class="message-page">
      <tn-nav-bar
        fixed
        alpha
        backgroundColor="#020303"
        :isBack="false"
        fontColor="#FFFFFF">
        <!-- 使用左侧槽位 -->
        <view slot="left" class="nav-left">
          <view class="read-all-btn" @tap="markAllAsRead">
            <text class="tn-icon-read"></text>
            <text class="btn-text">一键已读</text>
          </view>
        </view>

        <view class="nav-title">
			聊天
        </view>
      </tn-nav-bar>

      <!-- 消息列表内容 -->
      <z-paging
        ref="chatPaging"
        v-model="displayMessages"
        @query="queryChatMessages"
        :default-page-size="999"
        :auto="false"
        :paging-style="{paddingTop: vuex_status_bar_height + 44 + 'px'}"
        :bg-color="'#020303'"
        :show-refresher-when-reload="true"
		:safe-area-inset-bottom="true"
        :refresher-enabled="true"
        :refresher-threshold="80"
        :refresher-default-text="'下拉刷新'"
        :refresher-pulling-text="'释放立即刷新'"
        :refresher-refreshing-text="'加载中...'"
        :loading-more-custom-style="{color: '#B3F73C'}"
        :show-loading-more-no-more-view="false"
        :hide-loading-more-when-no-more-and-inside-of-paging="true"
        :empty-view-text="'暂无消息'"
        :empty-view-reload-text="'点击刷新'"
        :show-empty-view-reload="true"
        :auto-show-back-to-top="true"
        :auto-clean-list-when-reload="false"
        :loading-more-enabled="false"
      >
        <!-- 消息分类标签 -->
        <template #top>
          <view class="message-tabs">
            <!-- 修改流动背景实现方式 -->
            <view class="tab-bg-container">
              <view
                class="tab-bg-slider"
                :style="{
                  transform: `translateX(${activeTabIndex * 100}%)`,
                  width: `${100 / messageTabs.length}%`
                }"
              ></view>
            </view>
            <view
              v-for="(tab, index) in messageTabs"
              :key="index"
              class="message-tab"
              :class="{ active: activeTab === tab.id }"
              @tap="setActiveTab(tab.id, index)"
            >
              <view class="tab-content">
                {{ tab.name }}
                <!-- 添加未读消息数量提示，仅当不是当前选中的标签时显示 -->
                <view class="unread-count" v-if="tab.id !== activeTab && getTabUnreadCount(tab.id) > 0">
                  {{ getTabUnreadCount(tab.id) }}
                </view>
              </view>
            </view>
          </view>
        </template>

        <template #bottom>
          <view style="height: 100rpx;"></view>
        </template>

        <!-- 消息列表内容 -->
        <view class="message-container">
          <!-- 置顶消息 -->
          <template v-if="pinnedMessages.length > 0">
            <view
              v-for="message in pinnedMessages"
              :key="message.id"
              class="message-item"
              @tap="goToChat(message)"
              @longpress="showMessageOptions(message, $event)"
              :class="{ 'pinned': true, 'muted': message.isMuted, 'vip-message': message.isVip }"
            >
              <view class="avatar">
                <image :src="message.avatar" :alt="message.username" mode="aspectFill"></image>
                <view class="online-indicator" v-if="message.isOnline"></view>
                <view class="muted-indicator" v-if="message.isMuted">
                  <text class="tn-icon-sound-close"></text>
                </view>
              </view>
              <view class="message-content">
                <view class="message-header">
                  <view class="username-container">
                    <view class="username" :class="{ 'username-vip': message.isVip }">{{ message.username }}</view>
                    <view v-if="message.intimacy > 0" class="intimacy-indicator" :class="'intimacy-level-' + message.intimacy">
                      <text class="tn-icon-like-fill"></text>
                      <text>{{message.intimacy}}</text>
                    </view>
                  </view>
                  <view class="time-container">
                    <view class="time">{{ message.time }}</view>
                  </view>
                </view>
				<view class="dd">
					<view class="message-preview" :class="{ 'message-muted': message.isMuted }">
					  {{ message.lastMessage }}
					</view>
					<view class="message-status">
					  <view class="unread-badge" v-if="message.unreadCount > 0">
					    {{ message.unreadCount }}
					  </view>
					</view>
				</view>
              </view>
            </view>
          </template>

          <!-- 非置顶消息 -->
          <template v-for="(messageList, timeCategory) in categorizedMessages">
            <view :key="timeCategory" v-if="messageList.length > 0">
              <view class="new-message-label">
                {{ timeCategoryLabel[timeCategory] || timeCategory }}
              </view>
              <view
                v-for="message in messageList"
                :key="message.id"
                class="message-item"
                @tap="goToChat(message)"
                @longpress="showMessageOptions(message, $event)"
                :class="{ 'muted': message.isMuted, 'vip-message': message.isVip }"
              >
                <view class="avatar">
                  <image :src="message.avatar" :alt="message.username" mode="aspectFill"></image>
                  <view class="online-indicator" v-if="message.isOnline"></view>
                  <view class="muted-indicator" v-if="message.isMuted">
                    <text class="tn-icon-sound-close"></text>
                  </view>
                </view>
                <view class="message-content">
                  <view class="message-header">
                    <view class="username-container">
                      <view class="username" :class="{ 'username-vip': message.isVip }">{{ message.username }}</view>
                      <view v-if="message.intimacy > 0" class="intimacy-indicator" :class="'intimacy-level-' + message.intimacy">
                        <text class="tn-icon-like-fill"></text>
                        <text>{{message.intimacy}}</text>
                      </view>
                    </view>
                    <view class="time-container">
                      <view class="time">{{ message.time }}</view>
                    </view>
                  </view>
				  <view class="dd">
					  <view class="message-preview" :class="{ 'message-muted': message.isMuted }">
					    {{ message.lastMessage }}
					  </view>
					  <view class="message-status">
					    <view class="unread-badge" v-if="message.unreadCount > 0">
					      {{ message.unreadCount }}
					    </view>
					  </view>
				  </view>
                </view>
              </view>
            </view>
          </template>
        </view>
      </z-paging>

      <!-- 上下文菜单 -->
      <view
        class="context-menu"
        v-if="contextMenuVisible"
        :style="{
          left: contextMenuPosition.x + 'px',
          top: contextMenuPosition.y + 'px'
        }"
        @touchmove.stop.prevent
      >
        <view class="menu-item" @tap="togglePinMessage">
          <text class="tn-icon-task menu-icon"></text>
          <text>{{ selectedMessage && selectedMessage.isPinned ? '取消置顶' : '置顶聊天' }}</text>
        </view>
        <view class="menu-item" @tap="toggleMuteMessage">
          <text class="tn-icon-sound-close menu-icon"></text>
          <text>{{ selectedMessage && selectedMessage.isMuted ? '取消免打扰' : '消息免打扰' }}</text>
        </view>
        <view class="menu-item delete" @tap="deleteMessage">
          <text class="tn-icon-delete menu-icon"></text>
          <text>删除聊天</text>
        </view>
      </view>

      <!-- 点击遮罩关闭上下文菜单 -->
      <view
        class="context-menu-mask"
        v-if="contextMenuVisible"
        @tap="closeContextMenu"
        @touchmove.stop.prevent
      ></view>
    </view>
  </layout>
</template>

<script>
import { mapState } from 'vuex';
import router from '@/utils/router';
import { getConversationList, readAllConversations, deleteConversation, setConversationTop, setConversationMute, clearConversationUnreadCount } from '@/api/im/conversation';
import { deleteAllMessages, readMessage } from '@/api/im/message';

export default {
  name: 'MessagePage',
  data() {
    return {
      // 视图控制
      activeTab: 'all', // 'all', 'close' 或 'system'
      activeTabIndex: 0, // 活跃标签的索引，用于流动效果

      // 显示的消息数据
      displayMessages: [],

      // 完整消息数据
      messagesOrigin: [],

      // 加载状态
      isLoadingMore: false,
      isRefreshing: false,

      // 上下文菜单相关
      contextMenuVisible: false,
      contextMenuPosition: { x: 0, y: 0 },
      selectedMessage: null,

      // 高度计算
      scrollViewHeight: 400,

      // 搜索功能
      searchQuery: '',
      isSearchActive: false,

      // 时间分类标签
      timeCategoryLabel: {
        today: '今天',
        yesterday: '昨天',
        earlier: '更早'
      },

      // 消息分类标签
      messageTabs: [
        { id: 'all', name: '全部' },
        { id: 'close', name: '密友' },
        { id: 'system', name: '系统通知' }
      ],

      // 是否已加载数据
      isDataLoaded: false,

      // 添加WebSocket监听器ID
      wsListenerId: '',
      // 添加当前用户ID
      currentUserId: '',

      // 默认匿名头像 - 使用带墨镜的匿名头像
      defaultAvatar: 'https://rbtnet.oss-cn-hangzhou.aliyuncs.com/f58cad729ce47acb65666e57496f5e2e0c8badfec8355cfc7d6f2645f8738e60.jpeg'
    };
  },
  computed: {
    ...mapState({
      vuex_status_bar_height: state => state.vuex_status_bar_height,
    }),

    // 根据当前activeTab过滤消息
    filteredMessages() {
      if (this.activeTab === 'all') {
        return this.messagesOrigin;
      } else if (this.activeTab === 'close') {
        return this.messagesOrigin.filter(msg => msg.intimacy > 0);
      } else if (this.activeTab === 'system') {
        return this.messagesOrigin.filter(msg =>
		  msg.targetType === 2 ||
		  msg.targetType === 3
        );
      }
      return this.messagesOrigin;
    },

    // 筛选置顶消息
    pinnedMessages() {
      return this.filteredMessages.filter(msg => msg.isPinned);
    },

    // 筛选今天的消息
    todayMessages() {
      return this.filteredMessages.filter(msg => !msg.isPinned && msg.timeCategory === 'today');
    },

    // 筛选昨天的消息
    yesterdayMessages() {
      return this.filteredMessages.filter(msg => !msg.isPinned && msg.timeCategory === 'yesterday');
    },

    // 筛选更早的消息
    earlierMessages() {
      return this.filteredMessages.filter(msg => !msg.isPinned && msg.timeCategory === 'earlier');
    },

    // 分类消息
    categorizedMessages() {
      return {
        today: this.todayMessages,
        yesterday: this.yesterdayMessages,
        earlier: this.earlierMessages
      };
    },

    // 未读消息总数
    totalUnreadCount() {
      return this.messagesOrigin.reduce((total, msg) => total + msg.unreadCount, 0);
    },

    // 密友未读消息数
    closeUnreadCount() {
      return this.messagesOrigin
        .filter(msg => msg.intimacy > 0)
        .reduce((total, msg) => total + msg.unreadCount, 0);
    },

    // 系统消息未读数
    systemUnreadCount() {
      return this.messagesOrigin
        .filter(msg =>
		  msg.targetType === 2 ||
		  msg.targetType === 3
        )
        .reduce((total, msg) => total + msg.unreadCount, 0);
    }
  },
  onLoad() {
    // 获取当前用户ID
    this.currentUserId = uni.getStorageSync('userId');

    // 添加WebSocket消息监听器
    this.setupWebSocketListener();
  },
  onShow() {
  	this.initData();
  },
  onUnload() {
    // 移除WebSocket消息监听器
    this.removeWebSocketListener();
  },
  onHide() {
    // 页面隐藏时不移除监听器，让消息能在后台更新
  },
  watch: {
    // 监听activeTab变化，更新显示的消息列表
    filteredMessages: {
      handler(val) {
        this.displayMessages = val;
      },
      immediate: true
    }
  },
  methods: {
    // 获取指定标签的未读消息数
    getTabUnreadCount(tabId) {
      if (tabId === 'all') {
        return this.totalUnreadCount;
      } else if (tabId === 'close') {
        return this.closeUnreadCount;
      } else if (tabId === 'system') {
        return this.systemUnreadCount;
      }
      return 0;
    },

    // 初始化数据
    initData() {
      // 初始化原始消息数据
      this.loadConversations();
    },

    // 从服务器加载会话列表
    async loadConversations() {
      try {

        const result = await getConversationList();
        if (result && Array.isArray(result)) {
          // 转换后端数据结构为前端需要的格式
          this.messagesOrigin = result.map(item => this.convertConversation(item));
        }
      } catch (error) {
        console.error('加载会话列表失败:', error);
        uni.showToast({
          title: '加载会话列表失败',
          icon: 'none'
        });
      } finally {
        // 标记数据已加载
        this.isDataLoaded = true;
      }
    },

    // 转换后端会话数据格式为前端需要的格式
    convertConversation(conversation) {
      // 从后端得到的会话数据中提取所需信息
      const { id, targetId, targetType, targetNickname, targetAvatar, lastMessage, lastMessageContent, unreadCount,
              lastMessageCreateTime, isTop, muted, intimacyLevel, isVip, isOnline, lastMessageType } = conversation;

      // 计算时间分类
      const timeCategory = this.calculateTimeCategory(lastMessageCreateTime);
      const displayTime = this.formatTime(lastMessageCreateTime);

      // 处理消息内容显示
      let displayMessage = '暂无消息';
      if (lastMessageContent) {
        // 根据消息类型处理
        if (lastMessageType === 2) {
          // 图片类型消息
          displayMessage = '[图片]';

          // 尝试解析图片JSON，以防需要其他处理
          try {
            const imageData = JSON.parse(lastMessageContent);
            if (imageData && imageData.url) {
              // 这里可以添加其他图片相关处理，目前仍然显示为[图片]
              displayMessage = '[图片]';
            }
          } catch (e) {
            // JSON解析失败，仍然使用默认文本
            console.log('图片消息解析失败:', e);
            displayMessage = '[图片]';
          }
        } else if (lastMessageType === 3) {
          // 语音类型消息
          displayMessage = '[语音]';
        } else if (lastMessageType === 4) {
          // 视频类型消息
          displayMessage = '[视频]';
        } else if (lastMessageType === 5) {
          // 文件类型消息
          displayMessage = '[文件]';
        } else {
          // 文本类型消息
          // 检查是否是JSON格式的内容
          try {
            const contentObj = JSON.parse(lastMessageContent);
            if (contentObj && contentObj.url) {
              // 如果包含url字段，可能是图片内容
              displayMessage = '[图片]';
            } else {
              // 其他JSON内容，直接显示
              displayMessage = lastMessageContent;
            }
          } catch (e) {
            // 不是JSON格式，直接显示内容
            displayMessage = lastMessageContent;
          }
        }
      } else if (lastMessage) {
        displayMessage = lastMessage.content;
      }

      return {
        id: id,
        username: targetNickname || `用户${targetId}`,
        avatar: targetAvatar || this.defaultAvatar,
        lastMessage: displayMessage,
        time: displayTime,
        unreadCount: unreadCount || 0,
        isOnline: isOnline || false,
        isPinned: isTop || false,
        isMuted: muted || false,
        timeCategory: timeCategory,
        intimacy: intimacyLevel || 0,
        isVip: isVip || false,
        targetId,
        targetType
      };
    },

    // 计算时间分类（今天、昨天、更早）
    calculateTimeCategory(timestamp) {
      if (!timestamp) return 'earlier';

      const messageDate = new Date(timestamp);
      const today = new Date();
      const yesterday = new Date();
      yesterday.setDate(today.getDate() - 1);

      if (messageDate.toDateString() === today.toDateString()) {
        return 'today';
      } else if (messageDate.toDateString() === yesterday.toDateString()) {
        return 'yesterday';
      } else {
        return 'earlier';
      }
    },

    // 格式化时间显示
    formatTime(timestamp) {
      if (!timestamp) return '';

      const messageDate = new Date(timestamp);
      const today = new Date();
      const yesterday = new Date();
      yesterday.setDate(today.getDate() - 1);

      if (messageDate.toDateString() === today.toDateString()) {
        // 今天的消息，显示时:分
        const hours = messageDate.getHours();
        const minutes = messageDate.getMinutes();
        return `${this.padZero(hours)}:${this.padZero(minutes)}`;
      } else if (messageDate.toDateString() === yesterday.toDateString()) {
        return '昨天';
      } else {
        // 判断是否是今年
        if (messageDate.getFullYear() === today.getFullYear()) {
          // 同一年显示月-日
          return `${messageDate.getMonth() + 1}-${messageDate.getDate()}`;
        } else {
          // 不同年显示年-月-日
          return `${messageDate.getFullYear()}-${messageDate.getMonth() + 1}-${messageDate.getDate()}`;
        }
      }
    },

    // 添加数字前导零函数
    padZero(num) {
      return num < 10 ? '0' + num : num;
    },

    // 初始化模拟消息数据（当API不可用时使用）
    initMockMessagesOrigin() {
      // 模拟数据
      this.messagesOrigin = [
        {
          id: 1,
          targetId: 1,
          targetType: 1,
          username: '锦鲤抄',
          avatar: 'https://picsum.photos/seed/user1/100',
          lastMessage: '你好！我看了你的照片，感觉很有气质，想认识一下',
          time: '09:40',
          unreadCount: 2,
          isOnline: true,
          isPinned: true,
          isMuted: false,
          timeCategory: 'today',
          intimacy: 3,
          isVip: true
        },
        {
          id: 2,
          username: '阿萨德',
          avatar: 'https://picsum.photos/seed/user2/100',
          lastMessage: '哪里还有我们一起看过的那家美食店啊？',
          time: '10:23',
          unreadCount: 0,
          isOnline: true,
          isPinned: true,
          isMuted: false,
          timeCategory: 'today',
          intimacy: 5,
          isVip: true
        },
        {
          id: 3,
          username: '游戏快乐',
          avatar: 'https://picsum.photos/seed/user3/100',
          lastMessage: '晚上八点开黑，不见不散！',
          time: '08:15',
          unreadCount: 5,
          isOnline: false,
          isPinned: false,
          isMuted: false,
          timeCategory: 'today',
          intimacy: 4
        },
        {
          id: 4,
          username: '系统通知',
          avatar: 'https://picsum.photos/seed/system/100',
          lastMessage: '您的账户已通过高级认证，解锁更多特权功能！',
          time: '07:02',
          unreadCount: 1,
          isOnline: false,
          isPinned: false,
          isMuted: false,
          timeCategory: 'today',
          intimacy: 0
        },
        {
          id: 5,
          username: '小红',
          avatar: 'https://picsum.photos/seed/user4/100',
          lastMessage: '我们的游戏卡组已经创建好了，速度来参加吧~',
          time: '昨天',
          unreadCount: 0,
          isOnline: true,
          isPinned: false,
          isMuted: false,
          timeCategory: 'yesterday',
          intimacy: 2,
          isVip: true
        },
        {
          id: 6,
          username: '冰淇淋',
          avatar: 'https://picsum.photos/seed/user5/100',
          lastMessage: '图片',
          time: '昨天',
          unreadCount: 0,
          isOnline: false,
          isPinned: false,
          isMuted: true,
          timeCategory: 'yesterday',
          intimacy: 1
        },
        {
          id: 7,
          username: '活动推送',
          avatar: 'https://picsum.photos/seed/activity/100',
          lastMessage: '新的线下活动已发布，点击查看详情',
          time: '前天',
          unreadCount: 0,
          isOnline: false,
          isPinned: false,
          isMuted: false,
          timeCategory: 'earlier',
          intimacy: 0
        }
      ];
    },

    // 查询消息列表
    queryChatMessages(pageNo, pageSize) {
      // 无论是否已加载过数据，都重新加载会话列表
      this.loadConversations().then(() => {
        this.$refs.chatPaging.complete(this.filteredMessages);
      }).catch(error => {
        console.error('刷新会话列表失败:', error);
        // 如果请求失败但已有数据，仍然返回当前数据
        if (this.isDataLoaded) {
          this.$refs.chatPaging.complete(this.filteredMessages);
        } else {
          this.$refs.chatPaging.complete([]);
        }
      });
    },

    // 设置活跃的消息分类标签 - 不再重新加载数据，只切换过滤条件
    setActiveTab(tabId, index) {
      this.activeTab = tabId;
      this.activeTabIndex = index;
      // 不再调用reload()，而是通过计算属性自动更新显示
    },

    // 跳转到聊天详情页
    goToChat(message) {
      // 标记该消息为已读
      if (message.unreadCount > 0) {
        const index = this.messagesOrigin.findIndex(m => m.id === message.id);
        if (index !== -1) {
          this.messagesOrigin[index].unreadCount = 0;
        }

        // 调用API清空会话未读消息数
        clearConversationUnreadCount(message.targetId || message.id, message.targetType || 1)
          .then(() => {
            // 更新Vuex中的未读计数
            this.$store.dispatch('websocket/resetUnreadCount');
          })
          .catch(error => {
            console.error('清空会话未读消息数失败:', error);
          });
      }

      // 跳转到聊天页面
      uni.navigateTo({
        url: `/pages/chat/index?id=${message.targetId}`
      });
    },

    // 标记所有消息为已读
    markAllAsRead() {
      uni.showLoading({
        title: '处理中...'
      });
      // 重置Vuex中的未读计数
      this.$store.dispatch('websocket/resetUnreadCount');
      // 调用API标记所有消息为已读
      readAllConversations().then(() => {
        // 更新本地消息未读状态
        this.messagesOrigin.forEach(message => {
          message.unreadCount = 0;
        });

        uni.showToast({
          title: '已全部标记为已读',
          icon: 'success'
        });
      }).catch(error => {
        console.error('标记全部已读失败:', error);
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }).finally(() => {
        uni.hideLoading();
      });
    },

    // 显示消息操作选项
    showMessageOptions(message, event) {
      // 添加震荡反馈
      uni.vibrateShort({
        success: () => {
          console.log('长按震动反馈成功');
        },
        fail: (err) => {
          console.error('长按震动反馈失败', err);
        }
      });

      // 阻止默认行为和冒泡
      event.stopPropagation();

      // 计算菜单位置
      const x = event.touches[0].clientX;
      const y = event.touches[0].clientY;

      // 更新上下文菜单状态
      this.selectedMessage = message;
      this.contextMenuPosition = { x, y };
      this.contextMenuVisible = true;
    },

    // 关闭上下文菜单
    closeContextMenu() {
      this.contextMenuVisible = false;
      this.selectedMessage = null;
    },

    // 切换消息置顶状态
    togglePinMessage() {
      // 添加震荡反馈
      uni.vibrateShort();

      if (!this.selectedMessage) return;

      const message = this.selectedMessage;
      const isPinned = !message.isPinned;

      // 调用API设置置顶状态
      setConversationTop(message.targetId || message.id, message.targetType || 1, isPinned)
        .then(() => {
          // 更新本地状态
          const index = this.messagesOrigin.findIndex(m => m.id === message.id);
          if (index !== -1) {
            this.messagesOrigin[index].isPinned = isPinned;
          }

          uni.showToast({
            title: isPinned ? '已置顶' : '已取消置顶',
            icon: 'success'
          });
        })
        .catch(error => {
          console.error('设置置顶状态失败:', error);
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          });
        })
        .finally(() => {
          this.closeContextMenu();
        });
    },

    // 切换消息免打扰状态
    toggleMuteMessage() {
      // 添加震荡反馈
      uni.vibrateShort();

      if (!this.selectedMessage) return;

      const message = this.selectedMessage;
      const isMuted = !message.isMuted;

      // 调用API设置免打扰状态
      setConversationMute(message.targetId || message.id, message.targetType || 1, isMuted)
        .then(() => {
          // 更新本地状态
          const index = this.messagesOrigin.findIndex(m => m.id === message.id);
          if (index !== -1) {
            this.messagesOrigin[index].isMuted = isMuted;
          }

          uni.showToast({
            title: isMuted ? '已设置免打扰' : '已取消免打扰',
            icon: 'success'
          });
        })
        .catch(error => {
          console.error('设置免打扰状态失败:', error);
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          });
        })
        .finally(() => {
          this.closeContextMenu();
        });
    },

    // 删除消息
    deleteMessage() {
      // 添加震荡反馈
      uni.vibrateShort();

      if (!this.selectedMessage) return;

      uni.showModal({
        title: '提示',
        content: '确定要删除此聊天吗？',
        success: res => {
          if (res.confirm) {
            const message = this.selectedMessage;

            // 调用API删除会话
            deleteConversation({
              targetId: message.targetId || message.id,
              targetType: message.targetType || 1
            })
              .then(() => {
                // 从本地列表移除
                const index = this.messagesOrigin.findIndex(m => m.id === message.id);
                if (index !== -1) {
                  this.messagesOrigin.splice(index, 1);
                }

                uni.showToast({
                  title: '已删除',
                  icon: 'success'
                });
              })
              .catch(error => {
                console.error('删除会话失败:', error);
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                });
              })
              .finally(() => {
                this.closeContextMenu();
              });
          } else {
            this.closeContextMenu();
          }
        }
      });
    },

    // 添加WebSocket监听器设置方法
    setupWebSocketListener() {
      // 移除已有的监听器，避免重复
      this.removeWebSocketListener();

      // 创建新的监听器ID
      this.wsListenerId = 'message-page-' + Date.now();

      // 添加监听器
      this.$webSocketManager.addListener(this.wsListenerId, this.handleWebSocketMessage);
      console.log('消息列表页面 - 添加WebSocket监听器:', this.wsListenerId);
    },

    // 移除WebSocket监听器方法
    removeWebSocketListener() {
      if (this.wsListenerId) {
        this.$webSocketManager.removeListener(this.wsListenerId);
        console.log('消息列表页面 - 移除WebSocket监听器:', this.wsListenerId);
        this.wsListenerId = '';
      }
    },

    // 处理WebSocket消息
    handleWebSocketMessage(message) {
      console.log('消息列表页面 - 收到WebSocket消息:', message);

      // 处理聊天消息
      if (message.type === 'im.message.send') {
        try {
          // 解析消息内容
          const content = typeof message.content === 'string' ?
            JSON.parse(message.content) : message.content;

          // 检查消息是否是发给当前用户的
          if (content.toUserId == this.currentUserId) {
            // 格式化消息内容用于显示
            let displayMessage = content.content;
            if (content.type === 2) {
              displayMessage = '[图片]';
            } else if (content.type === 3) {
              displayMessage = '[语音]';
            } else if (content.type === 4) {
              displayMessage = '[视频]';
            } else if (content.type === 5) {
              displayMessage = '[文件]';
            }

            // 计算时间分类和格式化时间
            const timeCategory = this.calculateTimeCategory(content.sendTime);
            const displayTime = this.formatTime(content.sendTime);

            // 检查会话是否已存在
            const conversationIndex = this.messagesOrigin.findIndex(item =>
              item.targetId == content.fromUserId && item.targetType == 1
            );

            if (conversationIndex !== -1) {
              // 会话已存在，更新最后消息和未读数
              const conversation = this.messagesOrigin[conversationIndex];

              // 更新会话信息
              this.$set(this.messagesOrigin, conversationIndex, {
                ...conversation,
                lastMessage: displayMessage,
                time: displayTime,
                timeCategory: timeCategory,
                unreadCount: conversation.unreadCount + 1
              });

              // 如果当前会话不是置顶的，需要将它移到同一时间分类的最前面
              if (!conversation.isPinned) {
                // 从数组中移除
                this.messagesOrigin.splice(conversationIndex, 1);

                // 找到合适的插入位置
                let insertIndex = 0;
                // 跳过所有置顶消息
                while (insertIndex < this.messagesOrigin.length && this.messagesOrigin[insertIndex].isPinned) {
                  insertIndex++;
                }

                // 在正确位置插入
                this.messagesOrigin.splice(insertIndex, 0, {
                  ...conversation,
                  lastMessage: displayMessage,
                  time: displayTime,
                  timeCategory: timeCategory,
                  unreadCount: conversation.unreadCount + 1
                });
              }
            } else {
              // 会话不存在，创建新会话
              const newConversation = {
                id: 'temp_' + Date.now(), // 临时ID
                targetId: content.fromUserId,
                targetType: 1, // 假设1表示用户聊天
                username: content.fromUserNickname || `用户${content.fromUserId}`,
                avatar: content.fromUserAvatar || this.defaultAvatar,
                lastMessage: displayMessage,
                time: displayTime,
                unreadCount: 1,
                isOnline: false, // 默认值
                isPinned: false,
                isMuted: false,
                timeCategory: timeCategory,
                intimacy: 0, // 默认值
                isVip: false // 默认值
              };

              // 找到合适的插入位置(所有置顶消息之后)
              let insertIndex = 0;
              while (insertIndex < this.messagesOrigin.length && this.messagesOrigin[insertIndex].isPinned) {
                insertIndex++;
              }

              // 在正确位置插入
              this.messagesOrigin.splice(insertIndex, 0, newConversation);
            }

            // 强制更新视图
            this.displayMessages = [...this.filteredMessages];
          }
        } catch (e) {
          console.error('处理WebSocket消息失败:', e);
        }
      }
      // 处理消息撤回
      else if (message.type === 'im.message.recall') {
        try {
          // 解析消息内容
          const content = typeof message.content === 'string' ?
            JSON.parse(message.content) : message.content;

          console.log('收到消息撤回通知:', content);

          // 获取撤回消息的相关信息
          const { messageId, fromUserId, toUserId } = content;

          // 确定发送方和接收方
          let targetUserId;
          if (fromUserId == this.currentUserId) {
            // 如果是当前用户撤回的消息，目标用户是接收方
            targetUserId = toUserId;
          } else if (toUserId == this.currentUserId) {
            // 如果是发给当前用户的消息被撤回，目标用户是发送方
            targetUserId = fromUserId;
          }

          if (targetUserId) {
            // 查找对应的会话
            const conversationIndex = this.messagesOrigin.findIndex(item =>
              item.targetId == targetUserId && item.targetType == 1
            );

            if (conversationIndex !== -1) {
              // 获取当前会话
              const conversation = this.messagesOrigin[conversationIndex];

              // 如果有未读消息，减少未读计数
              let newUnreadCount = conversation.unreadCount;
              if (newUnreadCount > 0 && fromUserId != this.currentUserId) {
                // 只有不是自己撤回的消息且有未读计数时，才减少未读计数
                newUnreadCount -= 1;

                // 如果减少了未读计数，也减少Vuex中的未读总数
                this.$store.commit('websocket/DECREMENT_UNREAD_COUNT');
              }

              // 更新会话信息
              this.$set(this.messagesOrigin, conversationIndex, {
                ...conversation,
                lastMessage: '[消息已撤回]',
                unreadCount: newUnreadCount < 0 ? 0 : newUnreadCount, // 确保不会为负数
                // 时间保持不变
              });

              // 强制更新视图
              this.displayMessages = [...this.filteredMessages];
            }
          }
        } catch (e) {
          console.error('处理消息撤回失败:', e);
        }
      }
    }
  }
};
</script>

<style lang="scss">
.dd {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.message-page {
  background-color: #020303;

  .nav-title {
    font-size: 36rpx;
    font-weight: 700;
    color: #e0e0e0;
    position: relative;
    text-align: center;
  	height: 70rpx;

    &::after {
      content: '';
      position: absolute;
      bottom: -10rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 4rpx;
      background: linear-gradient(90deg, #8eac21, #B3F73C);
      border-radius: 2rpx;
    }
  }

  // 添加左侧导航按钮样式
  .nav-left {
    display: flex;
    align-items: center;
    margin-left: 30rpx;

    .read-all-btn {
      display: flex;
      align-items: center;
      background-color: rgba(179, 247, 60, 0.1);
      padding: 12rpx 24rpx;
      border-radius: 36rpx;
      color: #B3F73C;
	  z-index: 9999;

      .tn-icon-read {
        margin-right: 8rpx;
        font-size: 28rpx;
      }

      .btn-text {
        font-size: 24rpx;
        font-weight: 500;
      }

      &:active {
        opacity: 0.8;
        transform: scale(0.98);
      }
    }
  }

  // 添加右侧导航按钮样式
  .nav-right {
    display: flex;
    align-items: center;

    .read-all-btn {
      display: flex;
      align-items: center;
      background-color: rgba(179, 247, 60, 0.1);
      padding: 10rpx 20rpx;
      border-radius: 30rpx;
      color: #B3F73C;

      .tn-icon-read {
        margin-right: 8rpx;
        font-size: 28rpx;
      }

      .btn-text {
        font-size: 24rpx;
        font-weight: 500;
      }

      &:active {
        opacity: 0.8;
        transform: scale(0.98);
      }
    }
  }

  // 消息列表样式
  .message-container {
    padding: 30rpx;
	padding-top: 10rpx;
  }

  // 消息分类标签
  .message-tabs {
    display: flex;
    margin: 20rpx 30rpx;
    background-color: #1C1D22;
    border-radius: 12rpx;
    padding: 10rpx;
    position: relative;
    overflow: hidden;

    // 流动背景容器
    .tab-bg-container {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      padding: 10rpx;
      z-index: 1;
      pointer-events: none;
    }

    // 流动背景
    .tab-bg-slider {
      height: 100%;
      background-color: #B3F73C;
      border-radius: 8rpx;
      transition: transform 0.3s cubic-bezier(0.35, 0, 0.25, 1), width 0.3s cubic-bezier(0.35, 0, 0.25, 1);
    }

    .message-tab {
      flex: 1;
      text-align: center;
      padding: 15rpx 0;
      border-radius: 8rpx;
      position: relative;
      z-index: 2; // 确保内容在背景之上

      &.active {
        font-weight: bold;

        .tab-content {
          color: #020303;
        }
      }

      .tab-content {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        position: relative;
        font-size: 28rpx;
        color: #999999;
        padding: 0 16rpx;
        transition: color 0.3s;

        // 未读消息数量提示
        .unread-count {
          position: absolute;
          top: -10rpx;
          right: -12rpx;
          min-width: 28rpx;
          height: 28rpx;
          border-radius: 14rpx;
          background-color: #B3F73C;
          color: #020303;
          font-size: 18rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 4rpx;
          font-weight: bold;
          box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
          transform: scale(0.9);
        }
      }
    }
  }

  // 日期分类标签
  .new-message-label {
    font-size: 24rpx;
    color: #999999;
    margin-top: 30rpx;
    margin-bottom: 20rpx;
    padding-left: 30rpx;
  }

  // 消息项样式
  .message-item {
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    position: relative;
    border-bottom: none;

    &.pinned {
      background-color: rgba(179, 247, 60, 0.05);
      border-radius: 12rpx;
      margin-bottom: 10rpx;
      padding-bottom: 20rpx;
    }

    &.muted {
      opacity: 0.8;
    }

    &.vip-message {
      // 新的VIP消息样式，移除左侧黄色边框
      background-color: rgba(20, 20, 20, 0.3);
      border-radius: 12rpx;
      padding-bottom: 20rpx;
    }

    .avatar {
      width: 80rpx;
      height: 80rpx;
      position: relative;
      margin-right: 20rpx;
      flex-shrink: 0;

      image {
        width: 100%;
        height: 100%;
        border-radius: 40rpx;
      }

      .online-indicator {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 20rpx;
        height: 20rpx;
        border-radius: 10rpx;
        background-color: #B3F73C;
        border: 2rpx solid #020303;
      }

      .muted-indicator {
        position: absolute;
        right: -5rpx;
        bottom: -5rpx;
        width: 30rpx;
        height: 30rpx;
        border-radius: 15rpx;
        background-color: #1C1D22;
        display: flex;
        align-items: center;
        justify-content: center;

        text {
          font-size: 16rpx;
          color: #999999;
        }
      }
    }

    .message-content {
      flex: 1;
      overflow: hidden;
      position: relative;
      border-bottom: none;

      .message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8rpx;

        .username-container {
          display: flex;
          align-items: center;
          max-width: 70%;

          .username {
            font-size: 28rpx;
            color: #FFFFFF;
            font-weight: 500;
            margin-right: 10rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

            &.username-vip {
              color: #B3F73C;
            }
          }

          .intimacy-indicator {
            display: flex;
            align-items: center;
            font-size: 22rpx;
            padding: 4rpx 10rpx;
            border-radius: 20rpx;
            background-color: rgba(255, 255, 255, 0.1);
            color: #FFFFFF;

            text {
              &:first-child {
                margin-right: 6rpx;
                font-size: 20rpx;
              }
            }

            &.intimacy-level-1 {
              background-color: rgba(179, 247, 60, 0.1);
              color: #B3F73C;
            }

            &.intimacy-level-2 {
              background-color: rgba(179, 247, 60, 0.2);
              color: #B3F73C;
            }

            &.intimacy-level-3 {
              background-color: rgba(179, 247, 60, 0.3);
              color: #B3F73C;
            }

            &.intimacy-level-4 {
              background-color: rgba(179, 247, 60, 0.4);
              color: #B3F73C;
            }

            &.intimacy-level-5 {
              background-color: rgba(179, 247, 60, 0.5);
              color: #B3F73C;
            }

            &.intimacy-level-6 {
              background-color: rgba(179, 247, 60, 0.6);
              color: #020303;
            }
          }
        }

        .time-container {
          .time {
            font-size: 24rpx;
            color: #999999;
          }
        }
      }

      .message-preview {
        font-size: 24rpx;
        color: #CCCCCC;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;

        &.message-muted {
          color: #999999;
        }

        .sender-name {
          opacity: 0.7;
        }
      }
    }

    .message-status {

      .unread-badge {
        background-color: #B3F73C;
        color: #020303;
        font-size: 22rpx;
        min-width: 36rpx;
        height: 36rpx;
        border-radius: 18rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 10rpx;
        font-weight: bold;
      }
    }
  }

  // 上下文菜单样式
  .context-menu {
    position: absolute;
    width: 200rpx;
    background-color: #1C1D22;
    border-radius: 12rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
    z-index: 1000;

    .menu-item {
      padding: 20rpx;
      display: flex;
      align-items: center;
      border-bottom: 2rpx solid rgba(255, 255, 255, 0.05);

      &:last-child {
        border-bottom: none;
      }

      &.delete {
        color: #FF5252;
      }

      .menu-icon {
        margin-right: 10rpx;
        font-size: 28rpx;
      }

      text {
        font-size: 24rpx;
        color: #FFFFFF;
      }
    }
  }

  // 遮罩层
  .context-menu-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
  }
}
</style>
